//
//  ExperienceViewController.m
//  MemoryTravel
//
//  Created by dllo on 15/12/21.
//  Copyright © 2015年 fcx. All rights reserved.
//

#import "ExperienceViewController.h"
#import "ExperienceTableViewCell.h"
#import "ExperienceDetailViewController.h"
#import "ExperienceUserDetailViewController.h"
#import <CoreLocation/CoreLocation.h>
#import "ExperienceChooseCityViewController.h"

@interface ExperienceViewController ()<UITableViewDataSource, UITableViewDelegate, ExpreienceTabelViewCellDeledate, CLLocationManagerDelegate>

@property (nonatomic, strong)UITableView *myTableView;

@property (nonatomic, strong)NSMutableArray *bigArray;
@property (nonatomic, assign)BOOL isUpLoading;

@property (nonatomic, copy)NSString *next_start;
@property (nonatomic, copy)NSString *url;
@property (nonatomic, copy)NSString *city;
@property (nonatomic, copy)NSString *temp;

@property (nonatomic, strong)CLLocationManager *manager;

@property (nonatomic, strong)MBProgressHUD *hud;

@end

@implementation ExperienceViewController

- (void)viewWillDisappear:(BOOL)animated{
    self.temp = self.navigationItem.leftBarButtonItem.title;
}

- (void)viewWillAppear:(BOOL)animated{
    static BOOL isFirst = YES;
    if (!isFirst) {
        self.city = [[NSUserDefaults standardUserDefaults] objectForKey:@"localCity"];
        
        if (self.city == nil) {
            self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"全部" style:UIBarButtonItemStyleDone target:self action:@selector(leftBarButtonItemAction:)];
        } else{
            self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:self.city style:UIBarButtonItemStyleDone target:self action:@selector(leftBarButtonItemAction:)];
        }
        
        if ([self.navigationItem.leftBarButtonItem.title isEqualToString:self.temp]) {
            
        }
        else {
            self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            [self.hud show:YES];
            self.hud.labelText = @"正在切换城市...";
            
            [self getAFNetworkingData];
            [self.bigArray removeAllObjects];
            self.next_start = nil;
            self.isUpLoading = NO;
        }
    } else{
        isFirst = NO;
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"经历";
    
    self.city = [[NSUserDefaults standardUserDefaults] objectForKey:@"localCity"];
    
    if (self.city == nil) {
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"全部" style:UIBarButtonItemStyleDone target:self action:@selector(leftBarButtonItemAction:)];
    } else{
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:self.city style:UIBarButtonItemStyleDone target:self action:@selector(leftBarButtonItemAction:)];
    }
    
    self.manager = [[CLLocationManager alloc] init];
    [self.manager requestAlwaysAuthorization];
    self.manager.delegate = self;
    [self.manager startUpdatingLocation];
    
    self.bigArray = [NSMutableArray array];
    
    self.myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, Width, Height - 64 - 49) style:UITableViewStylePlain];
    self.myTableView.backgroundColor = [UIColor colorWithRed:250 / 255.0 green:245 / 255.0 blue:232 / 255.0 alpha:1.0];
    self.myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.myTableView.dataSource = self;
    self.myTableView.delegate = self;
    
    [self.view addSubview:self.myTableView];
    
    [self.myTableView registerClass:[ExperienceTableViewCell class] forCellReuseIdentifier:@"cell"];
    
    [self addHeaderRefresh];
    [self addFooterRefresh];
    
    NSLog(@"%@", self.next_start);
}

- (void)leftBarButtonItemAction:(UIBarButtonItem *)barButtonItem{
    ExperienceChooseCityViewController *chooseCityVC = [[ExperienceChooseCityViewController alloc] init];
                //模态动画
    chooseCityVC.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    chooseCityVC.city = [[NSUserDefaults standardUserDefaults] objectForKey:@"gpsCity"];
    [self presentViewController:chooseCityVC animated:YES completion:^{
        
        
    }];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    
    // 获取当前所在的城市名
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    //根据经纬度反向地理编译出地址信息
    [geocoder reverseGeocodeLocation:[locations lastObject] completionHandler:^(NSArray *array, NSError *error){
        
         if (array.count > 0){
             //详细地址
             CLPlacemark *placemark = [array objectAtIndex:0];
             
             //获取城市
             NSString *city = placemark.locality;
             
             if (!city) {
                 //四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
                 city = placemark.administrativeArea;
             }
             
             //将获得的所有信息显示到左上角按钮上
             NSRange range = [city rangeOfString:@"市"];
             self.city = [NSString stringWithFormat:@"%@", [city substringToIndex:range.location]];
             [[NSUserDefaults standardUserDefaults] setValue:self.city forKey:@"gpsCity"];
             [[NSUserDefaults standardUserDefaults] synchronize];
             if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"localCity"] isEqualToString:self.city]) {
                 
             } else{
                 
                 UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:[NSString stringWithFormat:@"系统检测到您在%@，是否切换?", self.city] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"切换", nil];
                 [alertView show];
             }
         }
         else if (error == nil && [array count] == 0){
             NSLog(@"No results were returned.");
         }
         else if (error != nil){
             NSLog(@"An error occurred = %@", error);
         }
     }];
    
    //系统会一直更新数据，直到选择停止更新，因为我们只需要获得一次经纬度即可，所以获取之后就停止更新
    [manager stopUpdatingLocation];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) {
        self.navigationItem.leftBarButtonItem.title = self.city;
        [[NSUserDefaults standardUserDefaults] setValue:self.city forKey:@"localCity"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        [self.hud show:YES];
        self.hud.labelText = @"正在切换城市...";
        
        [self getAFNetworkingData];
        [self.bigArray removeAllObjects];
        self.next_start = nil;
    }
}

- (void)addHeaderRefresh{
    
    self.myTableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        NSLog(@"下拉");
        
        self.isUpLoading = NO;
        
        //  重新请求数据
        [self getAFNetworkingData];
        
    }];
    [self.myTableView.header beginRefreshing];
}

- (void)addFooterRefresh{
    // 当上拉时触发该方法
    self.myTableView.footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
        
        NSLog(@"上拉");
        
        self.isUpLoading = YES;
        if (self.bigArray.count < 10) {
            [self.myTableView.footer endRefreshing];
        }
        else {
            [self getAFNetworkingData];
        }
        
    }];
}

- (void)getAFNetworkingData{
    if ([self.navigationItem.leftBarButtonItem.title isEqualToString:@"全部"]) {
        if (!self.isUpLoading) {
            [self.bigArray removeAllObjects];
            self.next_start = nil;
        }
        if (self.next_start == nil) {
            
            self.url = @"http://api.breadtrip.com/hunter/products/more/?start=0";
        }else{
            self.url = [NSString stringWithFormat:@"http://api.breadtrip.com/hunter/products/more/?start=%@",self.next_start];
        }
    } else{
        if (!self.isUpLoading) {
            [self.bigArray removeAllObjects];
            self.next_start = nil;
        }
        if (self.next_start == nil) {
            
            self.url = [NSString stringWithFormat:@"http://api.breadtrip.com/hunter/products/more/?start=0&city_name=%@&lat=38.882332558663585&lng=121.53934415009309",self.self.navigationItem.leftBarButtonItem.title];
            NSLog(@"哈哈");
        }
        else{
            self.url = [NSString stringWithFormat:@"http://api.breadtrip.com/hunter/products/more/?start=%@&city_name=%@&lat=38.882332558663585&lng=121.53934415009309", self.next_start,self.self.navigationItem.leftBarButtonItem.title];
        }
    }
    
    [AppTools getDataWithUrlStr:self.url andBlock:^(id result) {
        
        NSMutableDictionary *bigDic = result;
        NSMutableArray *array = [bigDic objectForKey:@"product_list"];
        self.next_start = [bigDic objectForKey:@"next_start"];
        
        for (NSMutableDictionary *dic in array) {
            ExperienceModel *model = [ExperienceModel modelWithDictionary:dic];
            [self.bigArray addObject:model];
        }
        
        if ([self.navigationItem.leftBarButtonItem.title isEqualToString:self.temp]) {
    
        } else {
            if (self.temp == nil) {
                
            } else {
                self.myTableView.contentOffset = CGPointMake(0, 0);
            }
            self.temp = self.navigationItem.leftBarButtonItem.title;
        }
        
        [self.hud hide:YES];
        [self.myTableView.header endRefreshing];
        [self.myTableView.footer endRefreshing];
        [self.myTableView reloadData];
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.bigArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellIdentifier = @"cell";
    ExperienceTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    ExperienceModel *model = [self.bigArray objectAtIndex:indexPath.row];
    cell.model = model;
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.expreienceTabelViewCellDeledate = self;
    
    NSLog(@"model === %@", model.title);
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 300;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    ExperienceDetailViewController *detailVC = [[ExperienceDetailViewController alloc] init];
    
    ExperienceModel *model = [self.bigArray objectAtIndex:indexPath.row];
    detailVC.product_id = model.product_id;
    detailVC.model = model;
    
    [self.navigationController pushViewController:detailVC animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)pushToWebView:(NSString *)person_id{
    ExperienceUserDetailViewController *userDetailVC = [[ExperienceUserDetailViewController alloc] init];
    userDetailVC.persen_id = person_id;
    [self.navigationController pushViewController:userDetailVC animated:YES];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
